/**
 * Factory: InboxFactory
 */
angular.module('EmailApp')
  .factory('InboxFactory', function InboxFactory ($q, $http, $location) {
    'use strict';
    var exports = {};
    exports.messages = [];

      function loadMessages() {
        console.log("load mails from emails.json");
        var deferred = $q.defer();
        return $http.get('json/emails.json')
          .success(function (data) {
            exports.messages = data;
            deferred.resolve(data);
          })
          .error(function (data) {
            deferred.reject(data);
          });
        return deferred.promise;
      };


    exports.goToMessage = function(id) {
      if ( angular.isNumber(id) ) {
        console.log('inbox/email/' + id)
        updateMessage(id, function(index) {
          exports.messages[index].read = true
        })
        $location.path('inbox/email/' + id)
      }
    }

      function updateMessage(id, callback) {
        for(var i=0;i<exports.messages.length;i++) {
          if(exports.messages[i].id == id) {
            callback( i)
          }
        }
      }

    exports.deleteMessage = function (id, index) {
      this.messages.splice(index, 1);
    }

    exports.getMessages = function (callback) {
      if(exports.messages.length == 0) {
        loadMessages().then(function(data) {
          console.log("inboxFactory:"+data)
          exports.messages = data.data;
          callback(data.data)
        });
      }else{
        callback(exports.messages);
      }
      //return exports.messages;
    };

    return exports;
  });
